package com.example.heimashop.view.activity;

import android.text.TextUtils;
import android.view.LayoutInflater;

import com.example.heimashop.base.BaseActivity;
import com.example.heimashop.database.AddressDao;
import com.example.heimashop.databinding.ActivityAddAddressBinding;
import com.example.heimashop.model.Address;
import com.example.heimashop.utils.ToastUtils;

/**
 * 添加/编辑收货地址页面
 */
public class AddAddressActivity extends BaseActivity<ActivityAddAddressBinding> {

    private AddressDao addressDao;
    private int addressId = -1; // -1表示新增，否则为编辑
    private Address currentAddress;

    @Override
    protected ActivityAddAddressBinding getViewBinding() {
        return ActivityAddAddressBinding.inflate(getLayoutInflater());
    }



    @Override
    protected void initView() {
        // 设置标题栏返回按钮
        binding.toolbar.setNavigationOnClickListener(v -> finish());

        // 初始化数据库
        addressDao = new AddressDao(this);

        // 获取地址ID（如果是编辑模式）
        addressId = getIntent().getIntExtra("address_id", -1);
        if (addressId != -1) {
            binding.toolbar.setTitle("编辑收货地址");
        }
    }

    @Override
    protected void initData() {
        // 如果是编辑模式，加载地址数据
        if (addressId != -1) {
            currentAddress = addressDao.getAddressById(addressId);
            if (currentAddress != null) {
                fillAddressData(currentAddress);
            }
        }
    }

    @Override
    protected void initListener() {
        // 保存按钮
        binding.btnSave.setOnClickListener(v -> saveAddress());
    }

    /**
     * 填充地址数据（编辑模式）
     */
    private void fillAddressData(Address address) {
        binding.etConsignee.setText(address.getConsignee());
        binding.etPhone.setText(address.getPhone());
        binding.etProvince.setText(address.getProvince());
        binding.etCity.setText(address.getCity());
        binding.etDistrict.setText(address.getDistrict());
        binding.etDetail.setText(address.getDetailAddress());
        binding.cbDefault.setChecked(address.isDefault());
    }

    /**
     * 保存地址
     */
    private void saveAddress() {
        // 获取输入内容
        String consignee = binding.etConsignee.getText().toString().trim();
        String phone = binding.etPhone.getText().toString().trim();
        String province = binding.etProvince.getText().toString().trim();
        String city = binding.etCity.getText().toString().trim();
        String district = binding.etDistrict.getText().toString().trim();
        String detail = binding.etDetail.getText().toString().trim();
        boolean isDefault = binding.cbDefault.isChecked();

        // 验证输入
        if (TextUtils.isEmpty(consignee)) {
            ToastUtils.showShort(this, "请输入收货人");
            return;
        }
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showShort(this, "请输入手机号码");
            return;
        }
        if (!isValidPhone(phone)) {
            ToastUtils.showShort(this, "请输入正确的手机号码");
            return;
        }
        if (TextUtils.isEmpty(province)) {
            ToastUtils.showShort(this, "请输入省份");
            return;
        }
        if (TextUtils.isEmpty(city)) {
            ToastUtils.showShort(this, "请输入城市");
            return;
        }
        if (TextUtils.isEmpty(district)) {
            ToastUtils.showShort(this, "请输入区/县");
            return;
        }
        if (TextUtils.isEmpty(detail)) {
            ToastUtils.showShort(this, "请输入详细地址");
            return;
        }

        // 创建或更新地址对象
        Address address;
        if (addressId == -1) {
            // 新增
            address = new Address();
        } else {
            // 编辑
            address = currentAddress;
        }

        address.setConsignee(consignee);
        address.setPhone(phone);
        address.setProvince(province);
        address.setCity(city);
        address.setDistrict(district);
        address.setDetailAddress(detail);
        address.setDefault(isDefault);

        // 保存到数据库
        long result;
        if (addressId == -1) {
            result = addressDao.addAddress(address);
        } else {
            result = addressDao.updateAddress(address);
        }

        if (result != -1) {
            // 如果设置为默认地址，更新数据库
            if (isDefault) {
                if (addressId == -1) {
                    // 新增的地址，使用返回的ID
                    addressDao.setDefaultAddress((int) result);
                } else {
                    // 编辑的地址，使用原有ID
                    addressDao.setDefaultAddress(addressId);
                }
            }

            ToastUtils.showShort(this, addressId == -1 ? "添加成功" : "保存成功");
            setResult(RESULT_OK);
            finish();
        } else {
            ToastUtils.showShort(this, addressId == -1 ? "添加失败" : "保存失败");
        }
    }

    /**
     * 验证手机号码格式
     */
    private boolean isValidPhone(String phone) {
        return phone.matches("^1[3-9]\\d{9}$");
    }
}
